import { _decorator, CCString, Component, EditBox, Label, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('BasePage')
export class BasePage extends Component {
    @property(CCString)
    protected prefix: string = '#';
    protected onLoad(): void {
        this.autoBindNode();
    }

    private autoBindNode(target: Node = this.node) {
        if (!this.prefix) {
            return;
        }
        for (const nd of target.children) {
            if (nd.name.startsWith(this.prefix)) {
                const name = nd.name.substring(1);
                const clsName = target.constructor.name;
                const type = clsCompsMap[clsName]?.[name];
                if (type) {
                    this[name] = nd.getComponent(type);
                } else {
                    this[name] = nd;
                }
                console.log('this', this, this[name]);
            }
            this.autoBindNode(nd);
        }
    }
}

const clsCompsMap:{[key:string]: {[key:string]: typeof Component}} = {}

export function bindComp(type: typeof Component) {
    return function (target: BasePage, key: string) {
        const clsName = target.constructor.name;
        if (clsName) {
            clsCompsMap[clsName] = clsCompsMap[clsName] || {};
            clsCompsMap[clsName][key] = type;
        }
    };
}